<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>知识库管理</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
  <link rel="stylesheet" href="{{ url_for('static', filename='css/bootstrap-icons.css') }}">
  <style>
    .actions-column {
      width: 150px;
    }
    .action-btn {
      margin: 0 2px;
    }
    .model-tag {
      font-size: 0.85rem;
      padding: 0.2rem 0.5rem;
      border-radius: 1rem;
      background-color: #e9ecef;
      color: #495057;
      display: inline-block;
    }
    .search-modal .form-control:focus {
      border-color: #0d6efd;
      box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
    }
    .result-item {
      border-left: 3px solid #0d6efd;
      margin-bottom: 1rem;
      padding: 0.5rem 1rem;
      background-color: #f8f9fa;
    }
    .match-score {
      font-size: 0.9rem;
      color: #0d6efd;
      font-weight: 500;
    }
    .source-file {
      font-size: 0.8rem;
      color: #6c757d;
    }
    .btn-group .btn {
      margin: 0;
      border-radius: 0;
    }
    .btn-group .btn:first-child {
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
    }
    .btn-group .btn:last-child {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
    .btn-group .btn + .btn {
      margin-left: -1px;
    }
  </style>
</head>
<body>
<div class="container mt-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h2>知识库管理</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#knowledgeModal">
      <i class="bi bi-plus-lg"></i> 新建知识库
    </button>
  </div>

  <!-- 知识库列表 -->
  <div class="table-responsive">
    <table class="table table-hover">
      <thead>
        <tr>
          <th>知识库名称</th>
          <th>嵌入模型</th>
          <th>文档数量</th>
          <th>分块数量</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="knowledgeList">
        <!-- 动态填充 -->
      </tbody>
    </table>
  </div>

  <!-- 新建知识库模态框 -->
  <div class="modal fade" id="knowledgeModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">新建知识库</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <form id="knowledgeForm">
            <div class="mb-3">
              <label class="form-label">知识库名称 *</label>
              <input type="text" class="form-control" id="name" required>
            </div>
            <div class="mb-3">
              <label class="form-label">嵌入模型 *</label>
              <select class="form-select" id="embeddingModel" required>
                <!-- 动态填充可用模型 -->
              </select>
            </div>
            <div class="mb-3">
              <a href="#" id="advancedToggle" class="text-decoration-none">
                <i class="bi bi-gear"></i> 高级设置
              </a>
            </div>
            <div id="advancedSettings" class="d-none">
              <div class="mb-3">
                <label class="form-label">Collection 名称</label>
                <input type="text" class="form-control" id="collectionName" placeholder="留空将自动生成">
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="saveKnowledge">创建</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 知识库检索模态框 -->
  <div class="modal fade search-modal" id="searchModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">知识库检索</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="input-group mb-4">
            <input type="text" class="form-control" id="searchInput" placeholder="输入检索内容...">
            <button class="btn btn-primary" id="doSearch">
              <i class="bi bi-search"></i> 检索
            </button>
          </div>
          <div id="searchResults" class="mt-3">
            <!-- 检索结果将动态填充 -->
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
// Polyfill for crypto.randomUUID
if (!crypto.randomUUID) {
    crypto.randomUUID = function() {
        return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
            (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
        );
    };
}
</script>

<script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
<script>
// 修改：更新知识库列表，增加修改按钮
function loadKnowledgeList() {
  fetch('/api/knowledges')
    .then(response => {
      if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
      return response.json();
    })
    .then(data => {
      const knowledges = Array.isArray(data) ? data : [];
      const html = knowledges.map(k => `
        <tr>
          <td>${k.name}</td>
          <td><span class="model-tag">${k.embedding_model}</span></td>
          <td>${k.doc_count}</td>
          <td>${k.segment_count}</td>
          <td>
            <div class="btn-group">
              <a href="/documents?knowledge_id=${k.id}" class="btn btn-sm btn-outline-primary">
                <i class="bi bi-upload"></i>
              </a>
              <button class="btn btn-sm btn-outline-primary" onclick="openSearch('${k.id}')">
                <i class="bi bi-search"></i>
              </button>
              <button class="btn btn-sm btn-outline-primary" onclick="openEdit('${k.id}', '${k.name}', '${k.embedding_model}', '${k.collection_name}')">
                <i class="bi bi-pencil"></i>
              </button>
              <!-- 暂时注释掉删除按钮
              <button class="btn btn-sm btn-outline-danger" onclick="deleteKnowledge('${k.id}')">
                <i class="bi bi-trash"></i>
              </button>
              -->
            </div>
          </td>
        </tr>
      `).join('');
      document.getElementById('knowledgeList').innerHTML = html;
    })
    .catch(error => {
      console.error('Loading knowledge list failed:', error);
      document.getElementById('knowledgeList').innerHTML = 
        '<tr><td colspan="5" class="text-center text-danger">加载失败，请刷新重试</td></tr>';
    });
}

// 加载嵌入模型列表
function loadEmbeddingModels() {
  fetch('/api/knowledges/models')  // 修改为正确的API路径
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .then(data => {
      // 确保 data 是数组类型
      const models = Array.isArray(data) ? data : [];
      const html = models.map(model => 
        `<option value="${model}">${model}</option>`
      ).join('');
      document.getElementById('embeddingModel').innerHTML = html || '<option value="">暂无可用模型</option>';
    })
    .catch(error => {
      console.error('Loading models failed:', error);
      document.getElementById('embeddingModel').innerHTML = '<option value="">加载失败</option>';
    });
}

// 知识库检索
function openSearch(knowledgeId) {
  currentKnowledgeId = knowledgeId;
  document.getElementById('searchResults').innerHTML = '';
  document.getElementById('searchInput').value = '';
  new bootstrap.Modal(document.getElementById('searchModal')).show();
}

// 新增：全局变量用于存储正在编辑的知识库ID
let editingKnowledgeId = null;

// 新增：打开编辑对话框，只允许修改知识库名称
function openEdit(knowledgeId, currentName, currentEmbeddingModel, currentCollectionName) {
  editingKnowledgeId = knowledgeId;
  document.getElementById('editName').value = currentName;
  document.getElementById('editEmbeddingModel').value = currentEmbeddingModel;
  document.getElementById('editCollectionName').value = currentCollectionName;
  new bootstrap.Modal(document.getElementById('editKnowledgeModal')).show();
}

// 将所有事件监听器的绑定移到 DOMContentLoaded 事件中
document.addEventListener('DOMContentLoaded', () => {
    // 初始化加载
    loadKnowledgeList();
    loadEmbeddingModels();

    // 高级设置切换
    const advancedToggle = document.getElementById('advancedToggle');
    if (advancedToggle) {
        advancedToggle.addEventListener('click', (e) => {
            e.preventDefault();
            const advanced = document.getElementById('advancedSettings');
            if (advanced) {
                advanced.classList.toggle('d-none');
            }
        });
    }

    // 创建知识库
    const saveKnowledgeBtn = document.getElementById('saveKnowledge');
    if (saveKnowledgeBtn) {
        saveKnowledgeBtn.addEventListener('click', () => {
            const data = {
                name: document.getElementById('name').value,
                embedding_model: document.getElementById('embeddingModel').value,
                collection_name: document.getElementById('collectionName').value
            };

            fetch('/api/knowledges', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.error) {
                    alert(result.error);
                } else {
                    bootstrap.Modal.getInstance(document.getElementById('knowledgeModal')).hide();
                    loadKnowledgeList();
                }
            });
        });
    }

    // 知识库检索
    const doSearchBtn = document.getElementById('doSearch');
    if (doSearchBtn) {
        doSearchBtn.addEventListener('click', () => {
            const query = document.getElementById('searchInput').value;
            
            fetch(`/api/knowledges/${currentKnowledgeId}/search`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({query: query})
            })
            .then(response => response.json())
            .then(data => {
                // 确保results是数组
                const results = Array.isArray(data) ? data : [];
                const html = results.map(r => `
                    <div class="result-item">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <span class="match-score">匹配度: ${(r.score * 100).toFixed(1)}%</span>
                            <span class="source-file">来源: ${r.filename || '未知'}</span>
                        </div>
                        <div>${r.content || ''}</div>
                    </div>
                `).join('');
                document.getElementById('searchResults').innerHTML = html || '<div class="text-center text-muted">未找到相关结果</div>';
            })
            .catch(error => {
                console.error('Search failed:', error);
                document.getElementById('searchResults').innerHTML = 
                    '<div class="text-center text-danger">搜索失败，请重试</div>';
            });
        });
    }

    // 更新知识库名称
    const saveEditKnowledgeBtn = document.getElementById('saveEditKnowledge');
    if (saveEditKnowledgeBtn) {
        saveEditKnowledgeBtn.addEventListener('click', () => {
            const updatedName = document.getElementById('editName').value;
            fetch(`/api/knowledges/${editingKnowledgeId}`, {
                method: 'PATCH',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({ name: updatedName })
            })
            .then(response => response.json())
            .then(result => {
                if (result.error) {
                    alert(result.error);
                } else {
                    bootstrap.Modal.getInstance(document.getElementById('editKnowledgeModal')).hide();
                    loadKnowledgeList();
                }
            });
        });
    }
});
</script>

<!-- 修改编辑知识库模态框 -->
<div class="modal fade" id="editKnowledgeModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">修改知识库</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="editKnowledgeForm">
          <div class="mb-3">
            <label class="form-label">知识库名称 *</label>
            <input type="text" class="form-control" id="editName" required>
          </div>
          <div class="mb-3">
            <label class="form-label">嵌入模型</label>
            <input type="text" class="form-control" id="editEmbeddingModel" readonly>
          </div>
          <div class="mb-3">
            <label class="form-label">Collection 名称</label>
            <input type="text" class="form-control" id="editCollectionName" readonly>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="saveEditKnowledge">保存</button>
      </div>
    </div>
  </div>
</div>
</body>
</html>